package top.superflow.flow.runtime.resource

import top.superflow.core.pool.resource.ResourcePool
import top.superflow.exception.RequestUnsupportedException
import top.superflow.flow.config.Identifiable
import top.superflow.log.Loggable

import scala.beans.BeanProperty

class RuntimeResource  extends Identifiable with Loggable{

  @BeanProperty
  var scope : String = _

  private var resourcePool : ResourcePool[_] = null

  def initResourcePoll(resourcePool : ResourcePool[_]): Unit ={
    if(resourcePool != null){
      throw new RequestUnsupportedException("The resourcePool has been initialized already")
    }
    this.resourcePool = resourcePool
  }

  def refreshResourcePoll(resourcePool : ResourcePool[_]): Unit ={
    logger.info("The resource pool will be refreshed by {}", resourcePool)
    this.resourcePool = resourcePool
  }

  def get[T](clz : Class[T]): T ={
    if(this.resourcePool == null || this.resourcePool.getResourceAction == null){
      throw new RequestUnsupportedException("The resource pool has not been initialized yet!")
    }

    val resource = this.resourcePool.getResourceAction.get
    if(resource == null){
      return null.asInstanceOf[T]
    }

    return try {
      resource.asInstanceOf[T]
    } catch {
      case ce : ClassCastException => throw new RequestUnsupportedException("Are you sure you know the type of the resource", ce)
    }

  }

}
